define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'task/index',
                    add_url: 'task/add',
                    edit_url: 'task/edit',
                    del_url: 'task/del',
                    multi_url: 'task/multi',
                    table: 'task',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'task_id',
                sortName: 'task_id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'task_id', title: __('Task_id')},
                        {field: 'task_no', title: __('Task_no')},
                        {field: 'business_title', title: __('公司名称'),width: '100px'},
                        {field: 'task_title', title: __('任务酬劳'),width: '100px'},
                        {field: 'show_time', title: __('Show_time'), operate:'RANGE', addclass:'datetimerange'},
                        {field: 'task_num', title: __('Task_num')},
                        {field: 'task_price', title: __('Task_price'), operate:'BETWEEN'},
                        {
                            field: 'get_start_time', 
                            title: __('领取任务时间'),
                            formatter: Controller.api.formatter.get_time
                        },
                        {
                            field: 'sk_start_time', 
                            title: __('上刊时间'),
                            formatter: Controller.api.formatter.sk_time
                        },
                        {field: 'task_total_price', title: __('任务费用'), operate:'BETWEEN'},
                        {
                            field: 'task_num',
                            title: __('任务进度'),
//                            align: 'left',
//                            searchList: $.getJSON('example/bootstraptable/searchlist?search=a&field=row[user_id]'),
                            formatter: Controller.api.formatter.task_schedule
                        },
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        //自定义栏位,custom是不存在的字段
                        {
                            field: 'task_id', 
                            title: __('操作'), 
                            operate: false, 
                            width: '80px',
                            formatter: Controller.api.formatter.opt
                        },
                        
//                        {field: 'sj_img', title: __('Sj_img'),formatter: Table.api.formatter.image},
//                        {field: 'xg_img', title: __('Xg_img'),formatter: Table.api.formatter.image},
//                        {field: 'push_position', title: __('Push_position'), visible:false, searchList: {"1":__('Push_position 1')}},
//                        {field: 'push_position_text', title: __('Push_position'), operate:false},
//                        {field: 'car_brand_list', title: __('Car_brand_list')},
//                        {field: 'car_type_list', title: __('Car_type_list')},
//                        {field: 'car_color_list', title: __('Car_color_list')},
//                        {field: 'reward_price', title: __('Reward_price'), operate:'BETWEEN'},
//                        {field: 'task_status', title: __('Task_status'), visible:false, searchList: {"1":__('Task_status 1'),"2":__('Task_status 2'),"3":__('Task_status 3'),"4":__('Task_status 4'),"5":__('Task_status 5'),"6":__('Task_status 6')}},
//                        {field: 'task_status_text', title: __('Task_status'), operate:false},
//                        {field: 'check_time', title: __('Check_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
//                        {field: 'refuse_text', title: __('Refuse_text')},
//                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
//                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
//                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                search: false,
                commonSearch: false,
            });
            
            //绑定TAB事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                // var options = table.bootstrapTable(tableOptions);
                var typeStr = $(this).attr("href").replace('#','');
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    if(typeStr != 'all'){
                        params.filter = JSON.stringify({task_status: typeStr});
                    }
//                    params.status = typeStr;
                    return params;
                };
                table.bootstrapTable('refresh', {});
                return false;

            });
            
            $(table).on("click", "[data-id].btn-over", function (e) {
                e.preventDefault();
                var id = $(this).data("id");
                var that = this;
                Layer.confirm(
                    __('结束该任务后，微信端用户无法申请该任务'),
                    {icon: 3, title: __('确定结束该任务吗？'), shadeClose: true},
                    function (index) {
                        $.post('task/over',{task_id:id},function(res){
                            table.bootstrapTable('refresh', {});
                        });
                        Layer.close(index);
                    }
                );
            });
            
            $(table).on("click", "[data-id].btn-check", function (e) {
                e.preventDefault();
                var id = $(this).data("id");
                var that = this;
                var url = $(that).data("url");
                Layer.confirm(
                    __('确定通过该任务吗？'),
                    {icon: 3, title: __('确定通过该任务吗？'), shadeClose: true},
                    function (index) {
                        $.post(url,{task_id:id},function(res){
                            table.bootstrapTable('refresh', {});
                        });
                        Layer.close(index);
                    }
                );
            });
            $(table).on("click", "[data-id].btn-pay", function (e) {
                e.preventDefault();
                var id = $(this).data("id");
                var that = this;
                var url = $(that).data("url");
                Layer.confirm(
                    __('确定支付该任务酬金吗？'),
                    {icon: 3, title: __('提示'), shadeClose: true},
                    function (index) {
                        $.post(url,{task_id:id},function(res){
                            if(res.code == 1){
                                table.bootstrapTable('refresh', {});
                            }
                            Layer.alert(res.msg);
                        });
                        Layer.close(index);
                    }
                );
            });
            
            $(table).on("click", "[data-id].btn-refuse", function (e) {
                e.preventDefault();
                var id = $(this).data("id");
                var that = this;
                var url = $(that).data("url");
                Layer.prompt({title: __('拒绝原因'), formType: 0}, function (value, index) {
                    Backend.api.ajax({
                        url: url+"?task_id="+id+"&refuse_text="+value,
                        data: $(that).closest("form").serialize()
                    },function(){
                        table.bootstrapTable('refresh', {});
                    });
                    
                    Layer.close(index);
                });
            });
            
            
            var options = table.bootstrapTable('getOptions');
            options.pageNumber = 1;
            options.queryParams = function (params) {
                params.filter = JSON.stringify({task_status: 1});
                return params;
            };
            table.bootstrapTable('refresh', {});

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        setbusiness: function () {
            Controller.api.bindevent();
        },
        api: {
            formatter: {//渲染的方法
                sk_time: function (value, row, index) {
                    var sk_start_time = value ? Moment(value * 1000).format('YYYY-MM-DD HH:mm:ss') : __('None');
                    var sk_end_time = row.sk_end_time ? Moment(row.sk_end_time * 1000).format('YYYY-MM-DD HH:mm:ss') : __('None');
                    return '<div class="input-group input-group-sm">'+sk_start_time+'<br/>'+sk_end_time+'</div>';
                },
                get_time: function (value, row, index) {
                    var get_start_time = value ? Moment(value * 1000).format('YYYY-MM-DD HH:mm:ss') : __('None');
                    var get_end_time = row.get_end_time ? Moment(row.get_end_time * 1000).format('YYYY-MM-DD HH:mm:ss') : __('None');
                    return '<div class="input-group input-group-sm">'+get_start_time+'<br/>'+get_end_time+'</div>';
                },
                task_schedule: function (value, row, index) {
                    var html = '<div class="input-group input-group-sm" style="text-align: center;"> - </div>';
                    if(row.task_status != '1'){
                        html = '<div class="input-group input-group-sm">'+row.complete_order_count+'人完成<span style="font-weight:bold"> / </span><br/>'+row.get_order_count+'人领取</div>';
                    }
                    return html;
                },
                opt:function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
//                    html += '<a href="user/detail/ids/127" class="btn-change text-success" style="margin-left: 10px;" title="用户信息" data-table-id="table" data-field-index="11" data-row-index="0" data-button-index="2"><b>用户信息</b></a>';
                    
                    var html = '<a href="task/detail/ids/'+row.task_id+'" class="btn-change text-success btn-addtabs" title="任务详情" data-table-id="table" data-field-index="11" data-row-index="0" data-button-index="2"><b>任务详情</b></a><br/>';
                    if(row.task_status ==3 || row.task_status ==4){
                        html += '<a class="text-success btn-over"  style="cursor:pointer" data-url="task/overtask" data-id="'+ row.task_id + '"><b>结束任务</b></a>';
                    }else if(row.task_status ==1){
                        html += '<a class="text-success btn-check"  style="cursor:pointer" data-url="task/checkok" data-id="'+ row.task_id + '"><b>同意</b></a> | ';
                        html += '<a class="text-success btn-refuse"  style="cursor:pointer" data-url="task/checkno" data-id="'+ row.task_id + '"><b>拒绝</b></a>';
                    }else if(row.task_status ==2 ){
                        if(row.now_admin_id != 1){
                            html += '<a class="text-success btn-pay"  style="cursor:pointer" data-url="task/paytask" data-id="'+ row.task_id + '"><b>付款</b></a>';
                        }
                        
                    }
                    return html;
                }
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                Form.api.bindevent($("form[role=form1]"),function(){
                    setTimeout(function(){
                     location.reload();  
                    },1500);
                });
                //删除
                $(document).on("click", ".js-address-del", function () {
                    $(this).parent('.js-address-li').remove();
                    var address_list = [];
                    $('.js-address-li').each(function(){
                        address_list.push($(this).children('.js-address-text').text())
                    });
                    $('.js-address_list').val(address_list.join(','));
                });
                //添加
                $('.js-address-add').bind('click',function(){
                    var address_list = [];
                    $('.js-address-li').each(function(){
                        address_list.push($(this).children('.js-address-text').text())
                    });
                    
                    var province_text = '';
                    var city_text = '';
                    var area_text = '';
                    if(isNaN(parseInt($('.js-province').val())) || isNaN(parseInt($('.js-city').val())) || isNaN(parseInt($('.js-area').val()))){
                        Toastr.error("省市区必须选择完整");
                        return false;
                    }
                    if($('.js-province').val()){
                        province_text = $('.js-province').find("option:selected").text();
                    }
                    if($('.js-city').val()){
                        city_text = $('.js-city').find("option:selected").text();
                    }
                    if($('.js-area').val()){
                        area_text = $('.js-area').find("option:selected").text();
                    }
                    var li = '<li class="js-address-li">';
                        li +='    <span class="js-address-text">'+province_text+city_text+area_text+'</span>';
                        li +='    <a href="javascript:;" class="js-address-del" data-original-title="删除"><i class="fa fa-times"></i></a>';
                        li +='</li>';
                    $('.js-address-ul').append(li);
                    address_list.push(province_text+city_text+area_text);
                    $('.js-address_list').val(address_list.join(','));
                    $('.js-province').val('');
                    $('.js-city').val('');
                    $('.js-area').val('');
                });
                
                $('.js-all').bind('click',function(){
                    $(this).parents('.js-check').find('.js-single').attr('checked',false);
                });
                
                $('.js-single').bind('click',function(){
                    $(this).parents('.js-check').find('.js-all').attr('checked',false);
                });
                
                $(document).on("blur", ".js-task-price,.js-task-num", function () {
                    var obj = $(this);
                    if(isNaN(obj.val())){
                        obj.val('');
                        Layer.msg('必须填写数字');
                        return false;
                    }
                    var task_price = $('.js-task-price').val();
                    var task_num = $('.js-task-num').val();
                    if(task_price <= 0 && task_num <= 0){
                        return false;
                    }
                    var $task_total_pirce = (parseFloat(task_price) + 50) * parseInt(task_num);
                    $('.js-task-total').text($task_total_pirce);
                });
                
                $(".js-show-brand-ck").bind("click",function(){
                    var show_text = $(this).children('.js-show-txt').text();
                    if(show_text == '展开'){
                        $(this).children('.js-show-txt').text('收起');
                    }else{
                        $(this).children('.js-show-txt').text('展开');
                    }
                    $(".js-show-brand-list").slideToggle();
                });
                $(".js-show-type-ck").bind("click",function(){
                    var show_text = $(this).children('.js-show-txt').text();
                    if(show_text == '展开'){
                        $(this).children('.js-show-txt').text('收起');
                    }else{
                        $(this).children('.js-show-txt').text('展开');
                    }
                    $(".js-show-type-list").slideToggle();
                });
                $(".js-show-color-ck").bind("click",function(){
                    var show_text = $(this).children('.js-show-txt').text();
                    if(show_text == '展开'){
                        $(this).children('.js-show-txt').text('收起');
                    }else{
                        $(this).children('.js-show-txt').text('展开');
                    }
                    $(".js-show-color-list").slideToggle();
                });
            }
        }
    };
    return Controller;
});
